package com.tanhua.app.service;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.UserHolder;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.MovementsApi;
import com.tanhua.api.mongo.RecommendUserApi;
import com.tanhua.db.UserInfo;
import com.tanhua.mongo.Visitors;
import com.tanhua.vo.VisitorsVo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MovementsService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private MovementsApi movementsApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private RecommendUserApi recommendUserApi;

    public ResponseEntity findVisitors() {

        // 1 从redis中获取当前登录用户的时间
        String time = stringRedisTemplate.opsForValue().get("visitors_user_" + UserHolder.getUser().getId());
        List<VisitorsVo> visitorsVoList = new ArrayList<>();
        if(time!=null){
            // 2 有：带着当前用户的id去历史表中查访客的id
            List<Visitors> list= movementsApi.findVisitors(UserHolder.getUser().getId(),Long.parseLong(time));
            //再带着访客的id去查userInfo表
            if(CollectionUtil.isNotEmpty(list)){
                for (Visitors visitors : list) {
                    UserInfo userInfo = userInfoApi.findById(visitors.getVisitorUserId());
                    //封装
                    VisitorsVo vo = new VisitorsVo();
                    vo.setUserInfo(userInfo);
                    //取缘分值
                    Long score = recommendUserApi.findScore(visitors.getVisitorUserId(), UserHolder.getUser().getId());
                    vo.setFateValue(score);
                    visitorsVoList.add(vo);
                }
            }

        }

        // 3 没有：将当前时间作为当前用户的最后一次登录时间
        stringRedisTemplate.opsForValue().set("visitors_user_"+ UserHolder.getUser().getId(),System.currentTimeMillis()+"");

        return ResponseEntity.ok(visitorsVoList);

    }
}
